# -*- coding: utf-8 -*-

from odoo.http import request

from odoo_contrib import http as contrib_http
from odoo_contrib.parser import parse_with
from odoo_contrib.marshal import marshal_with

from ..schemas import parser
from ..schemas import marshals
from ..utils.exceptions import FrontendException
from ..utils.settings import Settings


@contrib_http.route('/exhibition')
class WechatUserFavouritesExhibitRepository(contrib_http.Controller):
    @contrib_http.route('/favourites/', methods=['GET'])
    @parse_with(parser.favourites.FavouritesRepositoryParser)
    @marshal_with(marshals.favourites.FavouritesRepositorySchema, envelope='data')
    def favourites_exhibit_list(self):
        params = self.parser.parse()
        page = params['page']
        page_size = Settings().page_size

        domains = [
            ('wechat_user', '=', request.wechat_user.id),
            ('exhibit.enabled', '=', True)
        ]
        favourites = request.env['exhibition.exhibit_favourites'].search(
            domains,
            offset=page_size * page,
            limit=page_size,
        )
        return {
            'entries': favourites,
            'count': request.env['exhibition.exhibit_favourites'].search_count(domains),
        }

    @contrib_http.route('/favourites/', methods=['POST'])
    @parse_with(parser.favourites.FavouritesParser)
    @marshal_with(marshals.favourites.FavouritesSchema, envelope='data')
    def add_favourites_exhibit(self):
        params = self.parser.parse()

        exhibit_id = params['exhibit_id']
        exhibit = request.env['exhibition.exhibit'].browse(exhibit_id)
        if not exhibit.exists():
            raise FrontendException(
                errcode=200401,
                params={
                    'exhibitId': exhibit_id,
                }
            )
        favourites = request.env['exhibition.exhibit_favourites'].create([
            {
                'exhibit': exhibit_id,
                'wechat_user': request.wechat_user.id,
            },
        ])
        return favourites

    @contrib_http.route('/favourites/', methods=['DELETE'])
    @parse_with(parser.favourites.FavouritesParser)
    def revoke_favourites_exhibit(self):
        params = self.parser.parse()

        exhibit_id = params['exhibit_id']
        favourites = request.env['exhibition.exhibit_favourites'].search([
            ('exhibit', '=', exhibit_id),
            ('wechat_user', '=', request.wechat_user.id)
        ])
        if len(favourites) == 0:
            raise FrontendException(
                errcode=200501,
                params={
                    'exhibitId': exhibit_id,
                }
            )
        favourites.unlink()
        return {
            'data': True
        }
